import { createSlice } from "@reduxjs/toolkit"
import request from '@/utils/request'
import { getToken, saveToken, clearToken } from "@/utils/token"

export const login = createSlice({
  // 1.命名空间
  name: 'login',

  // 2.初始化状态
  initialState: {
    token: getToken() || ''
  },

  // 3.定义reducers
  reducers: {
    // action函数(同步)
    setToken(preState, action) {
      preState.token = action.payload
    },

    delToken(preState) {
      preState.token = ''
    }
  }
})

// 导出action
export const { setToken, delToken } = login.actions

// 异步action
export function loginAction(formData) {
  return async (dispatch) => {
    // 获取token
    const { data: { data } } = await request.post('/authorizations', formData)
    dispatch(setToken(data.token))
    // 本地存储一份
    saveToken(data.token)
  }
}

export function logoutAction() {
  return (dispatch) => {
    dispatch(delToken())
    clearToken()
  }
}

// 导出reducer
export default login.reducer